<?php

namespace catchAdmin\shopping\controller;

use app\common\utils\Thumbnail;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use app\common\model\ShoppingSpu as SpuModel;
use catcher\exceptions\FailedException;

class ShoppingProduct extends CatchController
{
    protected $sup;

    public function __construct(SpuModel $sup)
    {
        $this->sup = $sup;
    }

    /**
     * 列表
     *
     * @time 2020年01月09日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->sup->getList());
    }

    /**
     * 添加
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function save(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();
//        if (!empty($req['image'])) {
//            $req['thumbnail_img'] = $this->convertThumbnails($req['image']);
//        }
        $req['deleted_at'] = 0;
        return CatchResponse::success($this->sup->addData($req));
    }

    /**
     * 更新
     *
     * @time 2020年01月09日
     * @param $id
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update($id, CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        //用原图生成缩略图并保存
//        if (!empty($req['image'])) {
//            $req['thumbnail_img'] = $this->convertThumbnails($req['image']);
//        }
        return CatchResponse::success($this->sup->saveData($id, $req));
    }

    /**
     * 删除
     *
     * @time 2020年01月09日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id): \think\response\Json
    {
        return CatchResponse::success($this->sup->destroy($id));
    }

    /**
     * 生成缩略图
     * @param string $image 原图片路径
     * @return string
     */
//    private function convertThumbnails(string $image): string
//    {
//        $str = str_replace('/', '\\', $image);
//        $str2 = str_replace('\files', '', $str);
//        $imgPath = config('filesystem.disks.local.root').$str2;
//
//        $newPath = pathinfo($imgPath, PATHINFO_DIRNAME) . '\\' .
//            pathinfo($imgPath, PATHINFO_FILENAME) . '_thumbnail.' .
//            pathinfo($imgPath, PATHINFO_EXTENSION);
//        $ret = (new Thumbnail())->generateThumbnail($imgPath, $newPath);
//        if (!$ret) {
//            throw new FailedException('生成缩略图失败');
//        }
//        return $newPath;
//    }

    /**
     * 获取产品
     * @return \think\response\Json
     */
    public function getShoppingProduct(): \think\response\Json
    {
        $list = $this->sup->field('id,name')->order('_id', 'desc')->select();
        return CatchResponse::success($list);
    }
}